package com.ruoyi.oos.overrun.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.oos.duty.domain.DutyClasses;
import com.ruoyi.oos.duty.domain.DutyTeam;
import com.ruoyi.oos.duty.domain.DutyTurns;
import com.ruoyi.oos.duty.mapper.DutyTeamMapper;
import com.ruoyi.oos.duty.service.IDutyClassesService;
import com.ruoyi.oos.duty.service.IDutyTurnsService;
import com.ruoyi.oos.overrun.domain.OverrunRecord;
import com.ruoyi.oos.overrun.mapper.OverrunRecordMapper;
import com.ruoyi.oos.overrun.service.IOverrunRecordCalService;
import com.ruoyi.oos.tag.domain.TagConfig;
import com.ruoyi.oos.tag.mapper.TagConfigMapper;
import com.ruoyi.oos.tag.mapper.TagGroupMapper;

import cn.hz.pi.api.PiApiUtil;
import cn.hz.pi.api.util.DateUtil;
import cn.hz.pi.api.util.TagValue;

@Service("overrunRecordCal")
public class OverrunRecordCalServiceImpl  implements IOverrunRecordCalService{
	
	@Autowired
	IDutyTurnsService turnsService;
	
	@Autowired
	IDutyClassesService classesService;
	
	@Autowired
	TagGroupMapper groupMapper;
	
	@Autowired
	DutyTeamMapper teamMapper;
	
	@Autowired
	TagConfigMapper configMapper;
	
	@Autowired
	OverrunRecordMapper recordMapper;
   
	String startTime =null;
	String endTime1 =null;
	Long teamId =null;
	String teamname =null;
	
	
	/**
	 * 单限值与多限值
	 */
	public void calOverrunRecord(Date date,Long dutyid) {
		if(date == null) {
			date= new Date();
		}
		  this.getTime(date,dutyid);
		  
		  TagConfig config = new TagConfig();
			config.setCalctype("1");
	   //循环测点
	   List<TagConfig> configList = configMapper.selectTagConfigList(config);
	   for (TagConfig tagConfig : configList) {
		   try {
			   this.saveOverReturnRecord(tagConfig,dutyid);
		} catch (Exception e) {
			System.out.println("Error,测点计算失败-》"+tagConfig.getTagname());
		}
		   
	  }
	}
	
	/**
	 * 根据当前时间 和规则，取出开始时间，结束时间 及当前值次
	 * @param date
	 * @param dutyid
	 */
	public void getTime(Date  date,Long dutyid) {
		DutyTurns  turns =turnsService.getCurDutyTurns(date,dutyid);//当前班和值次
		
		teamId =turns.getTeamId();//当值
			DutyTeam team = new DutyTeam();
			team.setIdentify(teamId);
		     teamname =teamMapper.selectDutyTeamList(team).get(0).getName();//当值名称
		DutyClasses classes =classesService.selectDutyClassesById(turns.getClassesId()) ;//当班
		String beginTime = classes.getTime();//当班开始时间
		classes =new DutyClasses();
		classes.setDutyId(dutyid.intValue());
		List<DutyClasses> classesList = classesService.selectDutyClassesList(classes);//所有班(三班)
		String endTime = this.getNextClasses(date, classesList);//当班结束时间
		String nowTime =DateUtils.getDate(date);//轮值启用时间
		
		  startTime = nowTime+" "+beginTime;// 计算开始时间
		  endTime1 = nowTime+" "+endTime;// 计算结束时间
		  System.out.println("startTime"+startTime +" endTime1"+endTime1);
		Date begintime2 =DateUtils.parseDate(startTime);
		Date endTime2=DateUtils.parseDate(endTime1);
		if(endTime2.getTime()<begintime2.getTime()) {//如果开始时间大于结束时间，结束时间需要加一天
			endTime2=DateUtils.addDays(endTime2, 1);
			endTime1 =DateUtils.dateTime1(endTime2);
		}
		 
	}

	
	public void saveOverReturnRecord(TagConfig tagConfig,Long dutyid) {
		String tagName = tagConfig.getTagname();
		String tagPiName = tagConfig.getPitagname();
		String limitType = tagConfig.getLimittype();
		Long allTime = DateUtil.minBetween(startTime,endTime1);//总时间
		List<TagValue> list  =PiApiUtil.getValueList(null,tagPiName,startTime,endTime1, allTime.intValue());//规则
		
		if(limitType.equals("2") ||limitType.equals("1") ) {
			List<Map<String,Object>> tagList = configMapper.selectTagConfigListDetail(tagConfig);//查询多限值的上下限
			this.saveRecord(tagName, tagList, list, limitType,dutyid);
		}
		else if(limitType.equals("3")) {
			List<Map<String,Object>> tagList2 = configMapper.selectTagConfigListDetail2(tagConfig);//查询多限值的上下限
			this.saveDongtaiRecord(tagName, tagList2, list, allTime, limitType,dutyid);
		}
	}

	public void saveDongtaiRecord(String tagName,List<Map<String,Object>> tagList,List<TagValue> list,Long allTime,String limitType,Long dutyid) {
		this.deleteRecord(tagName, startTime, endTime1,limitType);//删除
		for (Map<String, Object> map : tagList) {
			String type = map.get("type").toString();
			Object obj = map.get("pitag");
			if(obj!=null) {
				String calcstr = obj.toString();
				List<OverrunRecord> upList =new ArrayList<>();
				List<TagValue> dongtailist =PiApiUtil.getCalCulation(null, calcstr, startTime, endTime1,  allTime.intValue());
				if(type.equals("1") ) {
					  upList =this.getDongtaiUpList(list,dongtailist);
				}
				
				if(type.equals("2") ){
					// upList =this.getDongtaiUpList(list,dongtailist);
				}
				Long groupId =Long.parseLong(map.get("groupid").toString());
				Long tagId =Long.parseLong(map.get("id").toString());
				String calctype = map.get("calctype").toString();
				String limittype = map.get("limittype").toString();
				String level = StringUtils.convertStr(map.get("level"));
				String groupname =map.get("groupname").toString();
				String pitagname = map.get("pitagname").toString();
					for (OverrunRecord recordBean : upList) {
						recordBean.setGroupid(groupId);
						recordBean.setTagid(tagId);
						recordBean.setIdentify(teamId);
						recordBean.setTimes(DateUtil.minDateBetween(recordBean.getStarttime(),recordBean.getEndtime()));
						//recordBean.setLimitval(limitval);
						 recordBean.setLevel(level);
						recordBean.setCalctype(calctype);
						recordBean.setLimittype(limittype);
						recordBean.setDatatype(type);
						recordBean.setTagname(tagName);
						recordBean.setPitagname(pitagname);
						recordBean.setGroupname(groupname);
						recordBean.setTeamname(teamname);
						recordBean.setDutyid(dutyid);
						recordMapper.insertOverrunRecord(recordBean);
					}
			}
			
			
		}
	}

	
	public void saveRecord(String tagName,List<Map<String,Object>> tagList,List<TagValue> list,String limitType,Long dutyid) {
		this.deleteRecord(tagName, startTime, endTime1,limitType);//删除
		for (Map<String, Object> map : tagList) {
			String type = map.get("type").toString();//上下线
			List<OverrunRecord> upList =new ArrayList<>();
			Float limitval =Float.parseFloat(map.get("limitval").toString());
			Float endLimitval =Float.parseFloat(map.get("endlimitval").toString());
			if(type.equals("1") ) {
			if	(limitType.equals("1") ||  limitType.equals("2")) {
				  upList =this.getUpList(list,limitval,endLimitval);
			}
			}
			
			if(type.equals("2") ){
				if(limitType.equals("1") ||   limitType.equals("2")) {
					 upList =this.getDownList(list,limitval,endLimitval);
			 }
			}
			Long groupId =Long.parseLong(map.get("groupid").toString());
			Long tagId =Long.parseLong(map.get("id").toString());
			String calctype = map.get("calctype").toString();
			String limittype = map.get("limittype").toString();
			String pitagname = map.get("pitagname").toString();
			String level = StringUtils.convertStr(map.get("level"));
			String groupname =map.get("groupname").toString();
				for (OverrunRecord recordBean : upList) {
					recordBean.setGroupid(groupId);
					recordBean.setTagid(tagId);
					recordBean.setIdentify(teamId);
					recordBean.setTimes(DateUtil.minDateBetween(recordBean.getStarttime(),recordBean.getEndtime()));
					recordBean.setLimitval(limitval);
					 recordBean.setLevel(level);
					recordBean.setCalctype(calctype);
					recordBean.setLimittype(limittype);
					recordBean.setDatatype(type);
					recordBean.setTagname(tagName);
					recordBean.setPitagname(pitagname);
					recordBean.setGroupname(groupname);
					recordBean.setTeamname(teamname);
					recordBean.setDutyid(dutyid);
					recordMapper.insertOverrunRecord(recordBean);
				}
		}
	}
	
	
	public void deleteRecord(String tagName,String startTime,String endTime,String limitType) {
		OverrunRecord record = new OverrunRecord();
		record.setTagname(tagName);
		record.setLimittype(limitType);
		record.setStarttime(DateUtils.parseDate(startTime));
		record.setEndtime(DateUtils.parseDate(endTime));
		recordMapper.deleteOverReturnRecordByBean(record);
	}
	
	public List<OverrunRecord> getUpList(List<TagValue> list,Float limitval,Float endLimitval) {
		 int flag = 0;
		 List<OverrunRecord> recordList = new ArrayList<OverrunRecord>();
		   OverrunRecord record  = new OverrunRecord();
		  	TagValue end =list.get(list.size()-1);
			if (limitval.floatValue() != endLimitval.floatValue()) {
				for (TagValue tagValue : list) {
					Float value = tagValue.getValue();
				if (value > limitval && flag == 0 && value <= endLimitval) {
					Date tagbeginTime = DateUtils.parseDate(tagValue.getTime());
					record.setStarttime(tagbeginTime);
					flag = 1;
				}
				if ((value <= limitval || value >= endLimitval) && flag == 1) {
					Date tagendTime = DateUtils.parseDate(tagValue.getTime());
					record.setEndtime(tagendTime);
					recordList.add(record);
					record = new OverrunRecord();
					flag = 0;
				}}

				if (end.getValue() > limitval && end.getValue() < endLimitval) {
					Date tagendTime = DateUtils.parseDate(end.getTime());
					record.setEndtime(tagendTime);
					recordList.add(record);
				}

			} else {
				for (TagValue tagValue : list) {
					Float value = tagValue.getValue();
				if (value > limitval && flag == 0) {
					Date tagbeginTime = DateUtils.parseDate(tagValue.getTime());
					record.setStarttime(tagbeginTime);
					flag = 1;
				}
				if ((value <= limitval) && flag == 1) {
					Date tagendTime = DateUtils.parseDate(tagValue.getTime());
					record.setEndtime(tagendTime);
					recordList.add(record);
					record = new OverrunRecord();
					flag = 0;
				}
				}
				if (end.getValue() > limitval) {
					Date tagendTime = DateUtils.parseDate(end.getTime());
					record.setEndtime(tagendTime);
					recordList.add(record);
				}
			
		}
	     	
		 return recordList;
	}
	
	public List<OverrunRecord> getDongtaiUpList(List<TagValue> list,List<TagValue> dongtailist) {
		 int flag = 0;
		 List<OverrunRecord> recordList = new ArrayList<OverrunRecord>();
		   OverrunRecord record  = new OverrunRecord();
		  	TagValue end =list.get(list.size()-1);
		  	TagValue limitend =dongtailist.get(list.size()-1);
		  	int i =0;
		  	
				for (TagValue tagValue : list) {
					Float limitval = dongtailist.get(i).getValue();
					i++;
					Float value = tagValue.getValue();
				if (value > limitval && flag == 0) {
					Date tagbeginTime = DateUtils.parseDate(tagValue.getTime());
					record.setStarttime(tagbeginTime);
					record.setLimitval(limitval);
					flag = 1;
				}
				if ((value <= limitval) && flag == 1) {
					Date tagendTime = DateUtils.parseDate(tagValue.getTime());
					record.setEndtime(tagendTime);
					record.setLimitval(limitval);
					recordList.add(record);
					record = new OverrunRecord();
					flag = 0;
				}
				}
				if (end.getValue() > limitend.getValue()) {
					Date tagendTime = DateUtils.parseDate(end.getTime());
					record.setEndtime(tagendTime);
					record.setLimitval(limitend.getValue());
					recordList.add(record);
				}
			
		       
	     	
		 return recordList;
	}
	
	
	
	public List<OverrunRecord> getDownList(List<TagValue> list,Float limitval,Float endLimitval) {
		 int flag = 0;
		 List<OverrunRecord> recordList = new ArrayList<OverrunRecord>();
		 OverrunRecord record  = new OverrunRecord();
		if(limitval.floatValue() == endLimitval.floatValue()) {
			 for (TagValue tagValue : list) {
			     	Float value =	tagValue.getValue();
			     	 if(value<limitval && flag==0) {
			     		Date tagbeginTime=DateUtils.parseDate(tagValue.getTime());
			     		 record.setStarttime(tagbeginTime);
			     		 flag=1;
			     	 }
			     	 if(value>=limitval && flag==1) {
			     		Date tagendTime=DateUtils.parseDate(tagValue.getTime());
			     	    record.setEndtime(tagendTime);
			     		recordList.add(record);
			     		record = new OverrunRecord();
			     		flag=0;
			     	 }
				}
				 TagValue end =list.get(list.size()-1);
				 if(end.getValue()<limitval) {
					Date tagendTime=DateUtils.parseDate(end.getTime());
					 record.setEndtime(tagendTime);
			     		recordList.add(record);
				 }
		}else {
			 for (TagValue tagValue : list) {
			     	Float value =	tagValue.getValue();
			     	 if(value<limitval && flag==0 && value>endLimitval) {
			     		Date tagbeginTime=DateUtils.parseDate(tagValue.getTime());
			     		 record.setStarttime(tagbeginTime);
			     		 flag=1;
			     	 }
			     	 if((value>=limitval || value <endLimitval ) && flag==1) {
			     		Date tagendTime=DateUtils.parseDate(tagValue.getTime());
			     	    record.setEndtime(tagendTime);
			     		recordList.add(record);
			     		record = new OverrunRecord();
			     		flag=0;
			     	 }
				}
				 TagValue end =list.get(list.size()-1);
				 if(end.getValue()<=limitval && end.getValue()>endLimitval) {
					Date tagendTime=DateUtils.parseDate(end.getTime());
					 record.setEndtime(tagendTime);
			     		recordList.add(record);
				 }
			
		}
	
		 return recordList;
	}
	
	public  String getNextClasses(Date date,List<DutyClasses> classes) {
		Date nowdate = DateUtils.getDateHHMMSS(date);
		List<Date> list = new ArrayList<Date>();
		for (DutyClasses class1 : classes) {
			String time =class1.getTime();
			Date date1 =DateUtils.getDateHHMMSSStr(time);
			list.add(date1);
		}
		for (int i = 0; i < list.size(); i++) {
			Date date1 = list.get(i);
			Date date2 = list.get(i+1);
			Date date3 = list.get(list.size()-1);
			if(nowdate.getTime()>= date3.getTime()) {
				return classes.get(0).getTime();
			} else if(nowdate.getTime() >= date1.getTime() &&  nowdate.getTime()< date2.getTime()) {
				return classes.get(i+1).getTime();
			}else if (nowdate.getTime() <= date1.getTime()) {
				return classes.get(list.size()-1).getTime();
			}
			
		}
		return null;
	}
}
